import {defineStore} from "pinia";
import {usePmDictApi} from "@/api/pm/dict";

type PmDictState = {
  dictData: Record<string, PmDict[]>;
}

export const usePmDictStore = defineStore('PmDict', {
  state: (): PmDictState => ({
    dictData: null
  }),
  actions: {
    loadDictData() {
      return new Promise((resolve, reject) => {
        usePmDictApi().listSimpleDictData().then((res) => {
          if (res.code === 0 && res.data) {
            // 设置数据
            const dictDataMap: Record<string, PmDict[]> =  {};
            res.data.forEach((dictData: PmDict) => {
              // 获得 dictType 层级
              const enumValueObj = dictDataMap[dictData.dictType]
              if (!enumValueObj) {
                dictDataMap[dictData.dictType] = []
              }
              // 处理 dictValue 层级
              dictDataMap[dictData.dictType].push({
                dictType: dictData.dictType,
                value: dictData.value,
                label: dictData.label,
                colorType: dictData.colorType,
                cssClass: dictData.cssClass
              })
            })
            this.dictData = dictDataMap;
          }
        }).finally(() => {
          resolve(true);
        })
      })
    },
  }
})
